package com.lwx.test;

import java.util.*;

/**
 * 众数
 */
public class ModeDemo {
    public static void main(String[] args) {
        int n = 5;
        int k = 3;
        int arr[] = {1,2,2,1,3};
        int[] ret = Mode(arr, n, k);
        for (int i = 0; i < ret.length; i++) {
            System.out.println(ret[i]);
        }
    }
    public static int[] Mode(int[] arr, int n, int k){
        int[] ret = new int[n-k+1];
        for (int i = 0; i <n-k+1; i++) {
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int j = i; j <i+k ; j++) {
                if(map.containsKey(arr[j])){
                    int times = map.get(arr[j]);
                    times ++;
                    map.put(arr[j],times);
                }else {
                    int times = 1;
                    map.put(arr[j],times);
                }
            }
            ArrayList<Integer> arrayList = new ArrayList<>();
            //将次数放入list中
            for(Map.Entry<Integer, Integer> entry : map.entrySet()){
                arrayList.add(entry.getValue());
            }
            Collections.sort(arrayList);
            //出现的最多次数
            int maxTimes = arrayList.get(arrayList.size() -1);
            ArrayList<Integer> maxMode = new ArrayList<>();
            //找出是哪几个元素是出现的最大次数
            for(Map.Entry<Integer, Integer> entry : map.entrySet()){
                if(entry.getValue().equals(maxTimes)){
                    maxMode.add(entry.getKey());
                }
            }
            Collections.sort(maxMode);
            //得到众数的最小值
            ret[i] = maxMode.get(0);
        }
        return ret;
    }
}
